﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.Framework;

namespace ZealandIT.MsBuildTasks.IO
{
    /// <summary>
    /// MSBuild task that creates directory(ies) and uses impersonation - if username/pw specified.
    /// This allows the operation to work over UNC / network paths.
    /// </summary>
    public class MkDir : BaseImpersonationTask
    {
        private ITaskItem[] _directories;

        /// <summary>
        /// Collection of directories as ITaskItem array that need to be created.
        /// </summary>
        [Required]
        public ITaskItem[] Directories
        {
            get { return _directories; }
            set { _directories = value; }
        }

        /// <summary>
        /// Main work for creating the directories takes place here - this method is called from its
        /// abstract base class' <see cref="BaseImpersonationTask.Execute"/> method.
        /// </summary>
        /// <returns>True if successful, else false.</returns>
        protected override bool ExecuteInternal()
        {
            foreach(ITaskItem item in _directories)
            {
                try
                {
                    if (item.ItemSpec.Length > 0 && !Directory.Exists(item.ItemSpec))
                    {
                        Log.LogMessage(string.Format("Creating directory \"{0}\"...", item.ItemSpec));
                        Directory.CreateDirectory(item.ItemSpec);
                        Log.LogMessage("..done.");
                    }
                }
                catch (Exception ex)
                {
                    Log.LogMessage("..FAILED.");
                    Log.LogErrorFromException(ex);
                    return false;
                }
            }
            return true;
        }
    }
}
